package com.cskaoyan.login;

import com.cskaoyan.utils.JDBCUtils;

import java.sql.*;

/**
 * 创建日期: 2022/10/08 15:14
 *
 * @author ciggar
 *
 * 登录的案例
 */
public class LoginDemo {

    public static void main(String[] args) throws SQLException {

//        boolean ret = login("adaf", "1234' or '1=1");
        // select * from user where username = '天明' and password ='xxx'

        // select * from user where username = 'adaf' and password ='1234' or '1=1'


//        Boolean ret = loginUsePreparedStatement("天明", "xxx");

        Boolean ret = loginUsePreparedStatement("adaf", "1234' or '1=1");


        if (ret) {
            System.out.println("登录成功！");
        }else {
            System.out.println("登录失败！");
        }


    }


    // 登录的方法
    public static boolean login(String username,String password) throws SQLException {

        Connection connection = JDBCUtils.getConnection();
        Statement statement = connection.createStatement();

        String sql = "select * from user where username = '"+username+"' and password ='" + password+"'";
        System.out.println("sql:" + sql);
        ResultSet resultSet = statement.executeQuery(sql);

        if (resultSet.next()) {
            return true;
        }else {
            return false;
        }
    }



    private static Boolean loginUsePreparedStatement(String username,String password) throws SQLException {

        //  1. 获取连接
        Connection connection = JDBCUtils.getConnection();

        // 2. 获取PreparedStatement对象
        // 会和MySQL服务器进行一次网络传输
        PreparedStatement preparedStatement = connection.prepareStatement("select * from user where username = ? and password = ?");


        // 3. 传递参数
        preparedStatement.setString(1,username);
        preparedStatement.setString(2,password);

        ResultSet resultSet = preparedStatement.executeQuery();

        // 4. 解析
        if (resultSet.next()) {
            return true;
        }else {
            return false;
        }

    }
}
